import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import thunkMiddlware from 'redux-thunk';

import rootReducer from './reducers/index.js';

// Used middlewares
const middlewares = [
    promiseMiddleware(),
    thunkMiddlware
];

// 开发环境开启 Logger
if (process.env.ENABLE_LOGGER) {
    const createLogger = require('redux-logger');
    middlewares.push(createLogger({
        actionTransformer: (action) => ({
            ...action,
            type: String(action.type)
        })
    }));
}

// 加载浏览器端处理 Websocket 中间件
if (process.env.BROWSER) {
    const websocketMiddleware = require('./middlewares/websocket-middleware.js').default;
    middlewares.push(websocketMiddleware());
}

const middlewareComposed = applyMiddleware(...middlewares);
const finalCreateStore = middlewareComposed(createStore);

/**
 * 配置 Redux Store
 * @param  {Object} initialState
 * @return {Object}
 */
export default function configureStore(initialState) {
    return finalCreateStore(rootReducer, initialState);
}